/*
 * @Author: 邵朋 
 * @Date: 2023-12-08 19:19:11
 * @LastEditors: 邵朋 
 * @LastEditTime: 2023-12-22 21:24:42
 * @FilePath: /YouDian/src/util/bluetoothUtil/hexUtil.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
///字符串转十六进制
export function stringToHex(str:string) {
     return parseInt(str, 16).toString();

  }

  ///十六进制转字符串
  export function hexToString(hex:any) {
    return parseInt(hex, 16).toString();

  }

///十进制数字转2进制
export function decimalNumberToBinary(decimal:number) {
    let binary = '';
    while (decimal > 0) {
      binary = (decimal % 2) + binary;
      decimal = Math.floor(decimal / 2);
    }
    return binary;
  }

  
 ///十进制字符串转2进制
export function decimalStringToBinary(decimalString:string) {
  // 将十进制字符串转换为整数
  let decimal = parseInt(decimalString);
 
  // 初始化二进制字符串
  let binary = '';
 
  // 使用循环将十进制数转换为二进制
  while (decimal > 0) {
    // 取余数
    let remainder = decimal % 2;
 
    // 将余数添加到二进制字符串的开头
    binary = remainder + binary;
 
    // 更新十进制数
    decimal = Math.floor(decimal / 2);
  }
 
  return binary;
}

///字符串转ascii
export function stringToASCII(str:string) {
  let asciiString = '';
  for (let i = 0; i < str.length; i += 2) {
    const hex = str.substr(i, 2);
    const decimal = parseInt(hex, 16);
    const ascii = String.fromCharCode(decimal);
    asciiString += ascii;
  }
  return asciiString;
  }


///十六进制字符串每2位一相加
export function hexStrAddByEveryTwoWord(hexArray:any)
{
    
    
    let count = 0;
    for(let i=0; i<hexArray.length ; i++)
    {
      let hexstr = hexArray[i]
        let decStr = hexToString(hexstr)
        console.log("hex:"+hexstr +'   dec:'+decStr);

        count += parseInt(decStr);
    }
    let hexStr = count.toString(16);
    
    switch (hexStr.length) {
        case 1:
            hexStr = "000" + hexStr;
            break;
        case 2:
            hexStr = "00" + hexStr;
            break;
        case 3:
            hexStr = "0" + hexStr;
            break;
        default:
            break;
    }
    console.log("count:"+count +'   hex:'+hexStr);

    return hexStr;
}

// ArrayBuffer转16进度字符串示例
export function ab2hex(buffer:any) {
  const hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('')
}

///十六进制字符串转换成ArrayBuffer
export function str2ab(str:string){

  const buffer = new ArrayBuffer(str.length / 2);
  let x = new Uint8Array(buffer);
  for (let i = 0; i < x.length; i++) {
      x[i] = parseInt(str.slice(2 * i,2 * i+ 2), 16)
  }
  return buffer;

}




export function hexToArrayBuffer(hexString:string) {
  const byteArray = new Uint8Array(hexString.length / 2);
  for (let i = 0; i < hexString.length; i += 2) {
    byteArray[i / 2] = parseInt(hexString.substr(i, 2), 16);
  }
  return byteArray.buffer;
}